<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/%E6%AD%A6%E6%B1%8932x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/%E6%AD%A6%E6%B1%8916x16.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib1/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib1/pace/pace-theme-center-simple.min.css">
  <script src="/lib1/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="前言React组件的更新极其依赖于组件的状态，而组件嵌套多层时，则可能会把父级的状态一层一层往下传递，这样的话再管理和使用都极其不便。Redux是JavaScript的状态容器，提供可预测化的状态管理，在React中使用Redux，可以把所有的state集中到组件顶部，能够灵活地将所有state分发给所有的组件，这样就极大方便开发者管理React中的状态，也方便不同组件间的通信。 Redux使用R">
<meta property="og:type" content="article">
<meta property="og:title" content="react修炼（二）-Redux">
<meta property="og:url" content="http://example.com/2021/11/11/react/react%E4%BF%AE%E7%82%BC(%E4%BA%8C)-Redux/index.html">
<meta property="og:site_name" content="Technological Blog">
<meta property="og:description" content="前言React组件的更新极其依赖于组件的状态，而组件嵌套多层时，则可能会把父级的状态一层一层往下传递，这样的话再管理和使用都极其不便。Redux是JavaScript的状态容器，提供可预测化的状态管理，在React中使用Redux，可以把所有的state集中到组件顶部，能够灵活地将所有state分发给所有的组件，这样就极大方便开发者管理React中的状态，也方便不同组件间的通信。 Redux使用R">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://example.com/image/react%E4%BF%AE%E7%82%BC(%E4%BA%8C)-Redux/MMA%7D1PBV9D1%5DLA%25%25P4OMJ67.png">
<meta property="og:image" content="http://example.com/image/react%E4%BF%AE%E7%82%BC(%E4%BA%8C)-Redux/image-20211111113443814.png">
<meta property="article:published_time" content="2021-11-11T04:18:39.000Z">
<meta property="article:modified_time" content="2021-11-11T15:47:34.703Z">
<meta property="article:author" content="Li Yudong">
<meta property="article:tag" content="react初学">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://example.com/image/react%E4%BF%AE%E7%82%BC(%E4%BA%8C)-Redux/MMA%7D1PBV9D1%5DLA%25%25P4OMJ67.png">

<link rel="canonical" href="http://example.com/2021/11/11/react/react%E4%BF%AE%E7%82%BC(%E4%BA%8C)-Redux/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>react修炼（二）-Redux | Technological Blog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Technological Blog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">IT小白的成长之旅</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="tags fa-fw"></i>标签<span class="badge">18</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="th fa-fw"></i>分类<span class="badge">14</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="archive fa-fw"></i>归档<span class="badge">95</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/tiarmor1" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/11/11/react/react%E4%BF%AE%E7%82%BC(%E4%BA%8C)-Redux/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/author.jpg">
      <meta itemprop="name" content="Li Yudong">
      <meta itemprop="description" content="">
    </span>
    
    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Technological Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          react修炼（二）-Redux
        </h1>
    
        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              
    
              <time title="创建时间：2021-11-11 12:18:39 / 修改时间：23:47:34" itemprop="dateCreated datePublished" datetime="2021-11-11T12:18:39+08:00">2021-11-11</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/react/" itemprop="url" rel="index"><span itemprop="name">react</span></a>
                </span>
            </span>
    
          
    
        </div>
      </header>
    
    
    
    
    <div class="post-body" itemprop="articleBody">
    
      
        <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>React组件的更新极其依赖于组件的状态，而组件嵌套多层时，则可能会把父级的状态一层一层往下传递，这样的话再管理和使用都极其不便。Redux是JavaScript的状态容器，提供可预测化的状态管理，在React中使用Redux，可以把所有的state集中到组件顶部，能够灵活地将所有state分发给所有的组件，这样就极大方便开发者管理React中的状态，也方便不同组件间的通信。</p>
<h1 id="Redux使用"><a href="#Redux使用" class="headerlink" title="Redux使用"></a>Redux使用</h1><p>Reudx并不依赖于任何库，因此除了和React一起使用以外，也可以搭配其他视图库一起使用；在Redux中有几个核心概念：1、store：一个数据容器，用来管理和保存这个项目的state，在整个应用中只能有一个store；2、state：一个对象，在state中存储相应的数据，则可以通过store提供的方法来获取state；3、action：一个通知命令，用于对state进行修改。通过store提供的方法，可以发起action完成对state的修改。</p>
<h2 id="API"><a href="#API" class="headerlink" title="API"></a>API</h2><h3 id="Reducer"><a href="#Reducer" class="headerlink" title="Reducer"></a>Reducer</h3><p>action是一个通知命令，本质上是JavaScript普通对象，在action中，必须包含一个字符串类型的type属性；该属性值代表要对state做何种操作。除了type属性外，开发者可以根据业务需求定义action的其他属性，最终action会通过store传入reducer函数中以完成对state的修改。</p>
<p><img src="/../../image/react%E4%BF%AE%E7%82%BC(%E4%BA%8C)-Redux/MMA%7D1PBV9D1%5DLA%25%25P4OMJ67.png" alt="img"></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123;createStore&#125; <span class="keyword">from</span> <span class="string">'redux'</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">reducer</span>(<span class="params">state=&#123;&#125;, action</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> state;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> store = createStore(reducer);</span><br><span class="line"><span class="comment">//利用createStore方法可以创建项目中的store</span></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">利用createStore方法创建store时，一定要调入reducer函数，该函数的名字可以根据语义自行定义，该函数会帮助开发者初始化项目的state</span></span><br><span class="line"><span class="comment">后期对state的修改也都会在该函数中进行。</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>Redux中所有的数据都被保存在同一个state对象中，通过store可以发起action修改命令对state进行修改。当发起修改执行时，store会把state和action传入reducer函数中，reducer接收到action后可以根据action的指令对state进行修改，并返回修改后的state。一个完整的reducer函数如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">reducer</span>(<span class="params">state=&#123;</span></span></span><br><span class="line"><span class="function"><span class="params">    count: <span class="number">1</span><span class="regexp">//</span>在这里设置state的初始值</span></span></span><br><span class="line"><span class="function"><span class="params">&#125;, action</span>) </span>&#123;</span><br><span class="line">    <span class="comment">//action.type代表修改指令，该指令可以自定义</span></span><br><span class="line">    <span class="keyword">switch</span>(action.type) &#123;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">"COUNT_PLUS"</span>:</span><br><span class="line">            <span class="comment">//根据action指令，修改state并返回新的state</span></span><br><span class="line">            <span class="keyword">return</span> &#123;<span class="attr">count</span>: state.count + <span class="number">1</span>&#125;;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">"COUNT_REDUCE"</span>:</span><br><span class="line">            <span class="keyword">return</span> &#123;<span class="attr">count</span>: state.count - <span class="number">1</span>&#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> state;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>reducer本质就是一个函数，该函数有两个参数state和action，另外该函数一定有返回值，返回值时修改后新得state，在编写reducer时，一定要注意它是一个纯函数。</p>
<p>纯函数：1、该函数的执行过程中无任何副作用，如:网络请求、DOM操作、定时器；2、如果函数的调用参数相同，则永远返回相同的结果，并不依赖于程序执行期间外部任何状态或数据的变化。必须只依赖于其输入参数。 </p>
<h3 id="Store"><a href="#Store" class="headerlink" title="Store"></a>Store</h3><p>store是保存数据的容器，是createStore生成的一个对象，而store对象提供的方法有：1、getState方法：该方法用于获取state；2、dispatch(action):该方法用于发起一个action；3、subscribe(listener):该方法会注册一个监听器监听state发生的变化，另外该方法的返回值会返回一个注销监听器的方法，用于取消监听器。这些方法的操作说明如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> React <span class="keyword">from</span> <span class="string">'react'</span>;</span><br><span class="line"><span class="keyword">import</span> ReactDOM <span class="keyword">from</span> <span class="string">'react-dom'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123;createStore&#125; <span class="keyword">from</span> <span class="string">'redux'</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">reducer</span>(<span class="params">state=&#123;</span></span></span><br><span class="line"><span class="function"><span class="params">    count: <span class="number">1</span>,<span class="regexp">//</span>在这里设置state的初始值</span></span></span><br><span class="line"><span class="function"><span class="params">&#125;, action</span>) </span>&#123;</span><br><span class="line">    <span class="comment">//action.type代表修改指令，该指令可以自定义</span></span><br><span class="line">    <span class="keyword">switch</span>(action.type) &#123;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">"COUNT_PLUS"</span>:</span><br><span class="line">            <span class="comment">//根据action指令，修改state并返回新的state</span></span><br><span class="line">            <span class="keyword">return</span> &#123;<span class="attr">count</span>: state.count + <span class="number">1</span>&#125;;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">"COUNT_REDUCE"</span>:</span><br><span class="line">            <span class="keyword">return</span> &#123;<span class="attr">count</span>: state.count - <span class="number">1</span>&#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> state;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">render</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> state = store.getState();</span><br><span class="line">    ReactDOM.render(</span><br><span class="line">    	&lt;div&gt;</span><br><span class="line">        &lt;button onClick=&#123;() =&gt; &#123;</span><br><span class="line">        	store.dispatch(&#123;<span class="attr">type</span>: <span class="string">"COUNT_REDUCE"</span>&#125;);</span><br><span class="line">    	&#125;&#125;&gt;-&lt;<span class="regexp">/button&gt;</span></span><br><span class="line"><span class="regexp">		&lt;span&gt;&#123;state.count&#125;&lt;/</span>span&gt;</span><br><span class="line">		&lt;button onClick=&#123;() =&gt; &#123;</span><br><span class="line">            store.dispatch(&#123;<span class="attr">type</span>: <span class="string">"COUNT_PLUS"</span>&#125;);</span><br><span class="line">        &#125;&#125;&gt;+&lt;<span class="regexp">/button&gt;</span></span><br><span class="line"><span class="regexp">		&lt;/</span>div&gt;, <span class="built_in">document</span>.getElementById(<span class="string">'root'</span>);</span><br><span class="line">    );</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> store = createStore(reducer);</span><br><span class="line"><span class="comment">//添加监听，当state发生变化时，重新渲染视图</span></span><br><span class="line"><span class="keyword">let</span> unSubscribe = store.subscribe(render);</span><br><span class="line"><span class="comment">//完成初次视图渲染</span></span><br><span class="line">render();</span><br><span class="line"><span class="comment">//10秒后取消对state变化的监听</span></span><br><span class="line">setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    unSubscribe();</span><br><span class="line">&#125;, <span class="number">10000</span>);</span><br></pre></td></tr></table></figure>

<p>在上述代码中，可以看到Redux的基本流程：基于reducer创建store，从store中获取state并传递给视图，当视图被操作时，通过dispatch发起一个action，store接收到action之后，会把state和action传递给reducer，reducer更新state并把新得state传递给视图进行更新。</p>
<p><img src="/../../image/react%E4%BF%AE%E7%82%BC(%E4%BA%8C)-Redux/image-20211111113443814.png" alt="image-20211111113443814"></p>
<h2 id="React-Redux"><a href="#React-Redux" class="headerlink" title="React-Redux"></a>React-Redux</h2><p>直接在React中去使用Redux会很麻烦，组件嵌套层级一多，就需要一层层传递store。React-Redux库则可以帮助开发者便捷地使用Redux。使用步骤如下：</p>
<p>1、新建src/store.js并写下以下代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123;createStore&#125; <span class="keyword">from</span> <span class="string">'redux'</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">countFn</span>(<span class="params">state=&#123;</span></span></span><br><span class="line"><span class="function"><span class="params">    count:<span class="number">1</span></span></span></span><br><span class="line"><span class="function"><span class="params">&#125;, action</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">switch</span>(action.type) &#123;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">"COUNT_PLUS"</span>:</span><br><span class="line">            <span class="keyword">return</span> &#123; <span class="attr">count</span>: state.count + <span class="number">1</span>&#125;;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">"COUNT_REDUCE"</span>:</span><br><span class="line">            <span class="keyword">return</span> &#123; <span class="attr">count</span>: state.count - <span class="number">1</span>&#125;;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> state;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> store = createStore(countFn);</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> store;</span><br></pre></td></tr></table></figure>

<p>2、创建好store之后，就可以通过React-Redux把store关联到项目中，React-Redux中提供了一个组件Provider，该组件就是其前文中说过的context中的Provider，它的作用就是向其后代子孙传递信息。在Provider中有一个store属性，该属性的属性值是创建好的store。另外需要注意：Redux提倡一个项目只有一个store，所以Provider应该在整个项目的最外层。修改src/index.js的代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> React <span class="keyword">from</span> <span class="string">'react'</span>;</span><br><span class="line"><span class="keyword">import</span> ReactDOM <span class="keyword">from</span> <span class="string">'react-dom'</span>;</span><br><span class="line"><span class="keyword">import</span> App <span class="keyword">from</span> <span class="string">'./App'</span>;</span><br><span class="line"><span class="keyword">import</span> store <span class="keyword">from</span> <span class="string">"./store"</span>;</span><br><span class="line"><span class="keyword">import</span> &#123;Provider&#125; <span class="keyword">from</span> <span class="string">"react-redux"</span>;</span><br><span class="line">ReactDOM.render(</span><br><span class="line">&lt;Provider store=&#123;store&#125;&gt;</span><br><span class="line">    &lt;App /&gt;</span><br><span class="line">&lt;<span class="regexp">/Provider&gt;,</span></span><br><span class="line"><span class="regexp">document.getElementById('root'));</span></span><br></pre></td></tr></table></figure>

<h3 id="connect"><a href="#connect" class="headerlink" title="connect"></a>connect</h3><p>通过Provider已经可以把Redux的store传递给项目中的各个组件，那在组件中2如何接收和修改store中的state呢？React-Redux中提供了一个connect方法用于接收Provider传递下来的store中的state和dispatch。</p>
<p>connect (state =&gt; newProps)(Component);</p>
<p>这是connect比较常见的写法，该代码含义为调用connect时，传递一个回调函数给connect，connect会把store中的state传递给这个回调函数。而在回调函数中，找出组件需要的部分，然后返回，这是connect (state =&gt; newProps)这段代码的意思。除此之外，connect方法还会返回一个函数，该函数接收一个参数，这个参数是要获取state或dispatch的组件。</p>
<p>该函数会调用传递进去的组件，并把connect回调函数执行后的返回值，以及dispatch方法和父组件传递进来的数据一块传递给该组件。另外，该函数执行完成之后会返回一个新的组件以供父级调用。修改aec/App.js的代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> React <span class="keyword">from</span> <span class="string">'react'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123;connect&#125; <span class="keyword">from</span> <span class="string">"react-redux"</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">App</span>(<span class="params">props</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> &#123;count, dispatch&#125; = props;</span><br><span class="line">    <span class="keyword">return</span> (<span class="xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span></span><br><span class="line">           &lt;button onClick=&#123;() =&gt; &#123;</span><br><span class="line">        dispatch(&#123;type: "COUNT_REDUCE"&#125;);</span><br><span class="line"><span class="xml">    &#125;&#125;&gt;-<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="xml">	<span class="tag">&lt;<span class="name">span</span>&gt;</span>&#123;count&#125;<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span></span><br><span class="line">	&lt;button onClick=&#123;() =&gt; &#123;</span><br><span class="line">        dispatch(&#123;type: "COUNT_PLUS"&#125;);</span><br><span class="line"><span class="xml">    &#125;&#125;&gt;+<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="xml">	<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">	);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">App = connect(<span class="function"><span class="params">state</span> =&gt;</span> state) (App);</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> App;</span><br></pre></td></tr></table></figure>

<h3 id="Hooks"><a href="#Hooks" class="headerlink" title="Hooks"></a>Hooks</h3><p>React-redux也新增加了hooks，其Hooks也只能在React函数组件或自定义Hooks中使用。</p>
<p>1、const state = useSelector(state =&gt; state)与connect类时，useSelector接收一个回调函数，该回调函数会被useSelector调用，并且会把store中的state传递给该回调函数。该回调函数必须有返回值，该返回值一般是在state中开发者想要使用的数据，该数据最终会被useSelector返回；</p>
<p>2、const dispatch = useDispatch()；调用useDispatch，Hook返回值为Redux的dispatch方法；</p>
<p>3、const store = useStore()；调用useStore，Hook会返回Redux的store。使用React-Redux的Hooks，对计数器的案例进行一个修改，示例代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> React <span class="keyword">from</span> <span class="string">'react'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123;useSelector, useDispach&#125; <span class="keyword">from</span> <span class="string">"react-redux"</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">App</span>(<span class="params">props</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> count = useSelector(<span class="function"><span class="params">state</span>=&gt;</span>state.count);</span><br><span class="line">  <span class="keyword">const</span> dispatch = useDispatch();</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    &lt;div&gt;</span><br><span class="line">      &lt;button onClick=&#123;()=&gt;&#123;</span><br><span class="line">          dispatch(&#123;</span><br><span class="line">            type:<span class="string">"COUNT_REDUCE"</span></span><br><span class="line">          &#125;);</span><br><span class="line">        &#125;&#125;&gt;-&lt;<span class="regexp">/button&gt;</span></span><br><span class="line"><span class="regexp">        &lt;span&gt;&#123;count&#125;&lt;/</span>span&gt;</span><br><span class="line">        &lt;button onClick=&#123;()=&gt;&#123;</span><br><span class="line">          dispatch(&#123;</span><br><span class="line">            type:<span class="string">"COUNT_PLUS"</span></span><br><span class="line">          &#125;);</span><br><span class="line">        &#125;&#125;&gt;+&lt;<span class="regexp">/button&gt;  </span></span><br><span class="line"><span class="regexp">    &lt;/</span>div&gt;</span><br><span class="line">  );</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> App;</span><br></pre></td></tr></table></figure>

<h2 id="Todos"><a href="#Todos" class="headerlink" title="Todos"></a>Todos</h2><p>下面我们简单地实现一个todos来对上面的React Hooks和Redux做一个实践。</p>
<h3 id="index-js"><a href="#index-js" class="headerlink" title="index.js"></a>index.js</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//index.js是整个文件的入口</span></span><br><span class="line"><span class="keyword">import</span> React <span class="keyword">from</span> <span class="string">'react'</span>;</span><br><span class="line"><span class="keyword">import</span> ReactDOM <span class="keyword">from</span> <span class="string">'react-dom'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123;Provider&#125; <span class="keyword">from</span> <span class="string">"react-redux"</span>;</span><br><span class="line"><span class="keyword">import</span> App <span class="keyword">from</span> <span class="string">"./App"</span>;</span><br><span class="line"><span class="keyword">import</span> store <span class="keyword">from</span> <span class="string">"./store"</span>;</span><br><span class="line"><span class="keyword">import</span> <span class="string">"./index.css"</span>;</span><br><span class="line">ReactDOM.render(</span><br><span class="line">    &lt;Provider store=&#123;store&#125;&gt;</span><br><span class="line">        &lt;App /&gt;</span><br><span class="line">    &lt;<span class="regexp">/Provider&gt;, </span></span><br><span class="line"><span class="regexp">    document.getElementById('root')</span></span><br><span class="line"><span class="regexp">);</span></span><br><span class="line"><span class="regexp">/</span>*</span><br><span class="line">在index.js中引入React-Redux，把store关联进整个项目，并用Provider包裹代码，提供数据上下文环境。</span><br><span class="line">*<span class="regexp">/</span></span><br></pre></td></tr></table></figure>

<h3 id="store-js"><a href="#store-js" class="headerlink" title="store.js"></a>store.js</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//调用createStore，传入reducer从而创建store对象；</span></span><br><span class="line"><span class="comment">//在index.js中，用Provider把Redux的store分发给项目的各个组件</span></span><br><span class="line"><span class="keyword">import</span> &#123;createStore&#125; <span class="keyword">from</span> <span class="string">"redux"</span>;</span><br><span class="line"><span class="keyword">import</span> reducer <span class="keyword">from</span> <span class="string">"./reducer"</span>;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> createStore(reducer);</span><br></pre></td></tr></table></figure>

<h3 id="reducer-js"><a href="#reducer-js" class="headerlink" title="reducer.js"></a>reducer.js</h3><p>在数据关联视图之前，先建立好数据模型，由于Todos中记录的是多项数据，所以使用数组保存相关数据。且每一项数据有两种状态以及待办事项的文字，所以每一项数据中记录三个字段：id(数据ID)、title(该数据的名字)、done(是否完成)。</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">state = [</span><br><span class="line">    &#123;</span><br><span class="line">        id : 0,</span><br><span class="line">        title : "示例数据",</span><br><span class="line">        done : true</span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">        id : 1,</span><br><span class="line">        title : "示例数据2",</span><br><span class="line">        done : true</span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">        id : 2,</span><br><span class="line">        title : "示例数据3",</span><br><span class="line">        done : false</span><br><span class="line">    &#125;,</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<p>有了数据模型后，我们再去创建store，在建立reducer时，我们也可以预测以下以后会发生的action，对reducer进行进一步完善。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*在reducer中，我们先想好并定义该案例中可能会执行的操作</span></span><br><span class="line"><span class="comment">在reducer中注意，最好每一次返回一个新对象</span></span><br><span class="line"><span class="comment">react部分特性在组件更新时候进行浅对比，如果返回的是一个原有对象，经常会造成组件不更新。</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">reducer</span>(<span class="params">state=[],action</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">switch</span>(action.type)&#123;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">"TODO_ADD"</span>:</span><br><span class="line">            <span class="keyword">return</span> [</span><br><span class="line">                ...state,</span><br><span class="line">                &#123;</span><br><span class="line">                    id: <span class="built_in">Date</span>.now(),</span><br><span class="line">                    title: action.title,</span><br><span class="line">                    done: <span class="literal">false</span></span><br><span class="line">                &#125;</span><br><span class="line">            ]</span><br><span class="line">        <span class="keyword">case</span> <span class="string">"TODO_DONE"</span>:</span><br><span class="line">            state.forEach(<span class="function"><span class="params">item</span>=&gt;</span>&#123;</span><br><span class="line">                <span class="keyword">if</span>(item.id === action.id)&#123;</span><br><span class="line">                    item.done = action.done </span><br><span class="line">                &#125;</span><br><span class="line">            &#125;)  </span><br><span class="line">            <span class="keyword">return</span> [...state];</span><br><span class="line">        <span class="keyword">case</span> <span class="string">"TODO_EDIT"</span>:</span><br><span class="line">            state.forEach(<span class="function"><span class="params">item</span>=&gt;</span>&#123;</span><br><span class="line">                <span class="keyword">if</span>(item.id === action.id)&#123;</span><br><span class="line">                    item.title = action.title; </span><br><span class="line">                &#125;</span><br><span class="line">            &#125;)  </span><br><span class="line">            <span class="keyword">return</span> [...state];</span><br><span class="line">        <span class="keyword">case</span> <span class="string">"TODO_REMOVE"</span>:</span><br><span class="line">            state=state.filter(<span class="function"><span class="params">item</span>=&gt;</span>item.id!==action.id);  </span><br><span class="line">            <span class="keyword">return</span> state;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">"TODO_REMOVE_DONE"</span>:</span><br><span class="line">            state=state.filter(<span class="function"><span class="params">item</span>=&gt;</span>(!item.done));</span><br><span class="line">            <span class="keyword">return</span> state;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> state;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> reducer;</span><br></pre></td></tr></table></figure>

<h3 id="App-js"><a href="#App-js" class="headerlink" title="App.js"></a>App.js</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*App.js是项目的起始点，在App.js中Todos和State两个组件要根据数据来决定是否显示</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="keyword">import</span> React, &#123; Fragment &#125; <span class="keyword">from</span> <span class="string">'react'</span>;</span><br><span class="line"><span class="keyword">import</span> Title <span class="keyword">from</span> <span class="string">'./title'</span>;</span><br><span class="line"><span class="keyword">import</span> Create <span class="keyword">from</span> <span class="string">'./create'</span>;</span><br><span class="line"><span class="keyword">import</span> Todos <span class="keyword">from</span> <span class="string">'./todos'</span>;</span><br><span class="line"><span class="keyword">import</span> State <span class="keyword">from</span> <span class="string">'./state'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; useSelector &#125; <span class="keyword">from</span> <span class="string">'react-redux'</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">App</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">let</span> data = useSelector(<span class="function"><span class="params">state</span>=&gt;</span>state);</span><br><span class="line">    <span class="keyword">return</span> (<span class="xml"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"todoapp"</span>&gt;</span></span></span><br><span class="line"><span class="xml">        <span class="tag">&lt;<span class="name">Title</span> /&gt;</span></span></span><br><span class="line">        &lt;div className="content"&gt;</span><br><span class="line">            &lt;Create /&gt;</span><br><span class="line">            &#123;</span><br><span class="line">              data.length&gt;0?&lt;Fragment&gt;</span><br><span class="line">                &lt;Todos /&gt;</span><br><span class="line">                &lt;State /&gt;</span><br><span class="line">              &lt;/Fragment&gt;</span><br><span class="line">              :</span><br><span class="line">              ""</span><br><span class="line">            &#125;</span><br><span class="line"><span class="xml">        <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="xml">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span>)</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> App;</span><br></pre></td></tr></table></figure>

<h3 id="create-js"><a href="#create-js" class="headerlink" title="create.js"></a>create.js</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">1、在create.js中把输入空设置为受控组件，以便获取输入内容，其实就是Vue的双向绑定；</span></span><br><span class="line"><span class="comment">2、添加ketdown事件，在键盘按下时，如果按下的是Enter键并且此时输入框不为空，则发起一个action添加一项todo</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="keyword">import</span> React, &#123; useState &#125; <span class="keyword">from</span> <span class="string">'react'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; useDispatch &#125; <span class="keyword">from</span> <span class="string">'react-redux'</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Create</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">const</span> [val,setVal] = useState(<span class="string">""</span>);</span><br><span class="line">    <span class="keyword">const</span> dispatch = useDispatch();</span><br><span class="line">    <span class="keyword">return</span> (<span class="xml"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"create-todo"</span>&gt;</span></span></span><br><span class="line">        &lt;input </span><br><span class="line">          id="new-todo" </span><br><span class="line">          placeholder="请输入要完成的事项" </span><br><span class="line">          autoComplete="off"</span><br><span class="line">          type="text"</span><br><span class="line">          value=&#123;val&#125;</span><br><span class="line">          onChange=&#123;(&#123;target&#125;)=&gt;&#123;</span><br><span class="line">              setVal(target.value);</span><br><span class="line">          &#125;&#125;</span><br><span class="line">          onKeyDown=&#123;(&#123;keyCode&#125;)=&gt;&#123;</span><br><span class="line">            if(keyCode === 13</span><br><span class="line">            &amp;&amp; val.trim())&#123;</span><br><span class="line">                dispatch(&#123;</span><br><span class="line">                  type: "TODO_ADD",</span><br><span class="line">                  title:val</span><br><span class="line">                &#125;);</span><br><span class="line">                setVal("")</span><br><span class="line">            &#125;</span><br><span class="line">          &#125;&#125;</span><br><span class="line"><span class="xml">        /&gt;</span></span><br><span class="line"><span class="xml">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span>)</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Create;</span><br></pre></td></tr></table></figure>

<h3 id="todo-js"><a href="#todo-js" class="headerlink" title="todo.js"></a>todo.js</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">在Todos中，根据当前的Todo数量来生成每一项todo，并把数据传递给对应的todo。</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="keyword">import</span> React <span class="keyword">from</span> <span class="string">'react'</span>;</span><br><span class="line"><span class="keyword">import</span> Li <span class="keyword">from</span> <span class="string">'./li'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; useSelector &#125; <span class="keyword">from</span> <span class="string">'react-redux'</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Todos</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> data = useSelector(<span class="function"><span class="params">state</span>=&gt;</span>state);</span><br><span class="line">    <span class="keyword">return</span> (<span class="xml"><span class="tag">&lt;<span class="name">ul</span> <span class="attr">id</span>=<span class="string">"todo-list"</span>&gt;</span></span></span><br><span class="line">        &#123;data.map(item=&gt;(&lt;Li </span><br><span class="line">            key=&#123;item.id&#125;</span><br><span class="line">            &#123;...item&#125;</span><br><span class="line"><span class="xml">        /&gt;))&#125;</span></span><br><span class="line"><span class="xml">    <span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span></span><br><span class="line">  )</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Todos;</span><br></pre></td></tr></table></figure>

<h3 id="li-js"><a href="#li-js" class="headerlink" title="li.js"></a>li.js</h3><p>Li组件中要做的事比较多，按照功能分为如下：</p>
<p>1、从props中解构出id、title、done；先把视图中显示的文字进行修改，再将复选框改为受控组件，并和done进行关联。</p>
<p>2、给destroy添加单击事件，单击时发起action删除本项todo。</p>
<p>3、添加编辑功能，基本上分为如下步骤：(1)：声明state，用于控制是否进入编辑状态    。当双击文本时进入编辑状态，当输入框失去焦点时，则退出编辑状态；</p>
<p>(2)：此时进入编辑状态时输入框没有获得焦点，则点击页面的其他区域时也不会触发输入框的失焦效果，这样可能会导致多个todo进入编辑状态。为解决这个问题，我们这里使用ref和effect，将声明ref和输入框进行绑定，声明effect检测编辑状态改变。当编辑状态改变，并且是进入编辑状态时，让输入框获得焦点。这样单击页面其他区域则会触发blur事件，让todo退出触发状态。</p>
<p>(3)：完成编辑功能：这里药注意编辑输入框的值，不能直接和title进行绑定做成受控组件。如果用户清空了输入框的值，则退出编辑状态，title也会变成空的。正确的做法是声明一个state，让state的初始值为title，输入框和该state绑定。退出编辑时，判断state是否为空，若为空则让state恢复为title，否则再对state进行修改。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> React, &#123; useState, useRef, useEffect &#125; <span class="keyword">from</span> <span class="string">'react'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; useDispatch &#125; <span class="keyword">from</span> <span class="string">'react-redux'</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Li</span> (<span class="params">props</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">let</span> &#123;id,title,done&#125; = props;</span><br><span class="line">    <span class="keyword">const</span> [isEdit,changeEdit] = useState(<span class="literal">false</span>);</span><br><span class="line">    <span class="keyword">const</span> dispatch = useDispatch();</span><br><span class="line">    <span class="keyword">let</span> edit = useRef();</span><br><span class="line">    <span class="keyword">let</span> [val,setVal] = useState(title);</span><br><span class="line">    useEffect(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(isEdit)&#123;</span><br><span class="line">            edit.current.focus();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;,[isEdit]);</span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">        &lt;li className=&#123;isEdit?<span class="string">"editing"</span>:<span class="string">""</span>&#125;&gt;</span><br><span class="line">            &lt;div className=&#123;<span class="string">"todo "</span>+(done?<span class="string">"done"</span>:<span class="string">""</span>)&#125;&gt;</span><br><span class="line">                &lt;div className=<span class="string">"display"</span>&gt;</span><br><span class="line">                    &lt;input </span><br><span class="line">                        className=<span class="string">"check"</span> </span><br><span class="line">                        type=<span class="string">"checkbox"</span></span><br><span class="line">                        checked=&#123;done&#125;</span><br><span class="line">                        onChange=&#123;(&#123;target&#125;)=&gt;&#123;</span><br><span class="line">                            dispatch(&#123;</span><br><span class="line">                                type:<span class="string">"TODO_DONE"</span>,</span><br><span class="line">                                id,</span><br><span class="line">                                done:target.checked</span><br><span class="line">                            &#125;)</span><br><span class="line">                        &#125;&#125;</span><br><span class="line">                    /&gt;</span><br><span class="line">                    &lt;div </span><br><span class="line">                        className=<span class="string">"todo-content"</span></span><br><span class="line">                        onDoubleClick=&#123;()=&gt;&#123;</span><br><span class="line">                            changeEdit(<span class="literal">true</span>);</span><br><span class="line">                        &#125;&#125;</span><br><span class="line">                    &gt;&#123;title&#125;&lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">                    &lt;span </span></span><br><span class="line"><span class="regexp">                        className="todo-destroy"</span></span><br><span class="line"><span class="regexp">                        onClick=&#123;()=&gt;&#123;</span></span><br><span class="line"><span class="regexp">                            dispatch(&#123;</span></span><br><span class="line"><span class="regexp">                                type:"TODO_REMOVE",</span></span><br><span class="line"><span class="regexp">                                id</span></span><br><span class="line"><span class="regexp">                            &#125;)</span></span><br><span class="line"><span class="regexp">                        &#125;&#125;</span></span><br><span class="line"><span class="regexp">                    &gt;&lt;/</span>span&gt;</span><br><span class="line">                &lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">                &lt;div className="edit"&gt;</span></span><br><span class="line"><span class="regexp">                    &lt;input </span></span><br><span class="line"><span class="regexp">                        className="todo-input" </span></span><br><span class="line"><span class="regexp">                        type="text"</span></span><br><span class="line"><span class="regexp">                        ref=&#123;edit&#125;</span></span><br><span class="line"><span class="regexp">                        value=&#123;val&#125;</span></span><br><span class="line"><span class="regexp">                        onChange=&#123;(&#123;target&#125;)=&gt;&#123;</span></span><br><span class="line"><span class="regexp">                            setVal(target.value);</span></span><br><span class="line"><span class="regexp">                        &#125;&#125;</span></span><br><span class="line"><span class="regexp">                        onBlur=&#123;()=&gt;&#123;</span></span><br><span class="line"><span class="regexp">                            if(val.trim())&#123;</span></span><br><span class="line"><span class="regexp">                                dispatch(&#123;</span></span><br><span class="line"><span class="regexp">                                    type:"TODO_EDIT",</span></span><br><span class="line"><span class="regexp">                                    id,</span></span><br><span class="line"><span class="regexp">                                    title:val</span></span><br><span class="line"><span class="regexp">                                &#125;)</span></span><br><span class="line"><span class="regexp">                            &#125; else &#123;</span></span><br><span class="line"><span class="regexp">                                setVal(title);</span></span><br><span class="line"><span class="regexp">                            &#125;</span></span><br><span class="line"><span class="regexp">                            changeEdit(false);</span></span><br><span class="line"><span class="regexp">                        &#125;&#125;</span></span><br><span class="line"><span class="regexp">                    /</span>&gt;</span><br><span class="line">                &lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">            &lt;/</span>div&gt;</span><br><span class="line">        &lt;<span class="regexp">/li&gt;</span></span><br><span class="line"><span class="regexp">    )</span></span><br><span class="line"><span class="regexp">&#125;</span></span><br><span class="line"><span class="regexp">export default Li;</span></span><br></pre></td></tr></table></figure>

<h3 id="state-js"><a href="#state-js" class="headerlink" title="state.js"></a>state.js</h3><p>在State组件中需要获取所有的数据，分别筛选出已完成和未完成的数量同步至视图中。另外单击已完成事项按钮时，发起一个action清空已完成的todo项。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> React <span class="keyword">from</span> <span class="string">'react'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123;useSelector,useDispatch&#125; <span class="keyword">from</span> <span class="string">"react-redux"</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">State</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">let</span> data = useSelector(<span class="function"><span class="params">state</span>=&gt;</span>state);</span><br><span class="line">    <span class="keyword">let</span> unDone = data.filter(<span class="function"><span class="params">item</span>=&gt;</span>(!item.done));</span><br><span class="line">    <span class="keyword">let</span> done = data.filter(<span class="function"><span class="params">item</span>=&gt;</span>item.done);</span><br><span class="line">    <span class="keyword">let</span> dispatch = useDispatch();</span><br><span class="line">    <span class="keyword">return</span> (<span class="xml"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"todo-stats"</span>&gt;</span></span></span><br><span class="line">            &lt;span className="todo-count"&gt;</span><br><span class="line">              &lt;span className="number"&gt;&#123;unDone.length&#125;&lt;/span&gt; &lt;span className="word"&gt;项待完成&lt;/span&gt;</span><br><span class="line"><span class="xml">            <span class="tag">&lt;/<span class="name">span</span>&gt;</span> </span></span><br><span class="line"><span class="xml">            &#123;</span></span><br><span class="line"><span class="xml">              done.length&gt;0?</span></span><br><span class="line">              &lt;span className="todo-clear"&gt;</span><br><span class="line">                &lt;a </span><br><span class="line">                  href="#"</span><br><span class="line">                  onClick=&#123;()=&gt;&#123;</span><br><span class="line">                    dispatch(&#123;</span><br><span class="line">                      type:"TODO_REMOVE_DONE"</span><br><span class="line">                    &#125;)</span><br><span class="line">                  &#125;&#125;</span><br><span class="line">                &gt;</span><br><span class="line">                    Clear &lt;span&gt;&#123;done.length&#125;&lt;/span&gt; 已完成事项</span><br><span class="line">                &lt;/a&gt;</span><br><span class="line"><span class="xml">              <span class="tag">&lt;/<span class="name">span</span>&gt;</span></span></span><br><span class="line"><span class="xml">              :""</span></span><br><span class="line"><span class="xml">            &#125; </span></span><br><span class="line"><span class="xml">        <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">    )</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> State;</span><br></pre></td></tr></table></figure>

<h2 id="中间件"><a href="#中间件" class="headerlink" title="中间件"></a>中间件</h2><p>Redux中一个项目只会有一个store，当项目变得越来越庞大时，reducer也会变得极其庞大，会使项目难以维护。为解决这个问题，开发者可以对reducer按照模块进行拆分，这样可以让reducer中的解构更加清晰，也便于维护。例如，现在有一个项目，其中有两个模块的数据：user、todo。reducer应该为以下格式：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">reducer</span>(<span class="params">state, action</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">switch</span>(action.type) &#123;</span><br><span class="line">            ...;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">        user:&#123;...&#125;,</span><br><span class="line">        todo:[...]</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>拆分后的代码结果如下：把user和tode的逻辑放在不同的函数里进行处理：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">user</span>(<span class="params">user=&#123;...&#125;, action</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">switch</span>(action.type) &#123;</span><br><span class="line">    	...</span><br><span class="line">	&#125;</span><br><span class="line">    <span class="keyword">return</span> user;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">todo</span>(<span class="params">todo=&#123;...&#125;, action</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">switch</span>(action.type) &#123;</span><br><span class="line">    	...</span><br><span class="line">	&#125;</span><br><span class="line">    <span class="keyword">return</span> todo;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">reducer</span>(<span class="params">state=&#123;&#125;, action</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">        user:user(state.user, action)</span><br><span class="line">        todo:todo(state.todo, action)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上述代码中，先声明了一个根reducer函数，然后在该函数中拆分出user和todo两个函数。创建store时只需要把reducer函数传递给createStore即可。这样就把不同模块的state管理，放在了不同函数中，将来要做修改时，会极大方便开发者定位代码进行维护。另外在Redux中有一个方法combineReducers(rootReducer)，可以帮助开发者快速合并多个reducer函数。</p>
<p>combineReducers(rootReducer)方法需要传入一个rootReducer对象，它会根据这个对象生成一个reducer方法，帮助开发者合并多个reducer。rootReducer是一个对象，对象的key值是将来生成的state的key值。属性值则是拆分后的各个reducer。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">combineReducers(&#123;</span><br><span class="line">    user: user,</span><br><span class="line">    todo: todo</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h3 id="redux-thunk"><a href="#redux-thunk" class="headerlink" title="redux-thunk"></a>redux-thunk</h3><p>Redux的核心操作比较简单，基于reducer创建store，利用dispatch发起action，reducer接收到action之后，再完成state的修改。但在实际工作时，发起action之后，到达reducer之前，会有一些额外的工作需要处理，如日志记录、数据请求等这些都属于副作用。而reducer本身是一个纯函数，这时就需要中间件。</p>
<p>middleware中间件：之前dispatch发起action之后，会直接把action传递到reducer中。使用了中间件之后。dispatch发起action之后，会先把action传递给中间件；中间件这时就可以做相关的副作用，处理完之后再由中间件把action传递给reducer。Redux社群中有很多优秀的中间件：日志系统redux-logger、异步中间件redux-saga、异步中间件redux-thunk。</p>
<p>下面是Redux-thunk的示例代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">在创建store时，引入中间件。在Redux中提供了applyMiddleware(...middlewares)方法；</span></span><br><span class="line"><span class="comment">项目要引入的中间件都可以传递进applyMiddleware，然后把applyMiddleware的返回值传递给createStore</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="keyword">import</span> &#123;createStore, applyMiddleware&#125; <span class="keyword">from</span> <span class="string">"redux"</span>;</span><br><span class="line"><span class="keyword">import</span> reducer <span class="keyword">from</span> <span class="string">"./reducer"</span>;</span><br><span class="line"><span class="keyword">import</span> thunk <span class="keyword">from</span> <span class="string">"redux-thunk"</span>;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="keyword">default</span> createStore(reducer, applyMiddleware(thunk));</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">添加完thunk后，在项目中就可以利用thunk来做中间处理了。使用了thunk之后，dispatch可以接收两种不同类型参数。</span></span><br><span class="line"><span class="comment">参数类型是对象时，不会经过中间件处理，而是把action发送到reducer中。</span></span><br><span class="line"><span class="comment">参数类型是函数时，会执行该函数，以及dispatch和getState两个方法传递给该函数，在函数中可以进行中间处理，如数据请求等；</span></span><br><span class="line"><span class="comment">处理完之后再调用dispatch更新state</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line">dispatch(<span class="function"><span class="keyword">function</span>(<span class="params">dispatch, getState</span>)</span>&#123;</span><br><span class="line">    http.get(<span class="string">"..."</span>).then(<span class="function">(<span class="params">res</span>) =&gt;</span> &#123;</span><br><span class="line">        dispatch(&#123;</span><br><span class="line">            type: <span class="string">"GET_DATA"</span>,</span><br><span class="line">            data: res.data</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>并不是所有的项目都需要用到Redux，同时在真实项目中，不建议所有的state都集中在Redux中处理，一般情况下只要把异步请求的数据和多个组件之间需要公用的数据，在Redux中集中管理即可。</p>

    </div>
    
    
    
    
    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      
    </div>
        <div class="reward-container">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/alipay.png" alt="Li Yudong 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Li Yudong
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://example.com/2021/11/11/react/react%E4%BF%AE%E7%82%BC(%E4%BA%8C)-Redux/" title="react修炼（二）-Redux">http://example.com/2021/11/11/react/react修炼(二)-Redux/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

    
      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/react%E5%88%9D%E5%AD%A6/" rel="tag"># react初学</a>
          </div>
    
        

    
        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/11/04/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/%E8%AE%BE%E8%AE%A1%E5%8E%9F%E5%88%99%E4%B8%8E%E7%BC%96%E7%A8%8B%E6%8A%80%E5%B7%A7/" rel="prev" title="设计原则与编程技巧">
      <i class="fa fa-chevron-left"></i> 设计原则与编程技巧
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/11/12/react/react%E4%BF%AE%E7%82%BC(%E4%B8%89)-router/" rel="next" title="react修炼（三）-router">
      react修炼（三）-router <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Redux使用"><span class="nav-number">2.</span> <span class="nav-text">Redux使用</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#API"><span class="nav-number">2.1.</span> <span class="nav-text">API</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Reducer"><span class="nav-number">2.1.1.</span> <span class="nav-text">Reducer</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Store"><span class="nav-number">2.1.2.</span> <span class="nav-text">Store</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#React-Redux"><span class="nav-number">2.2.</span> <span class="nav-text">React-Redux</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#connect"><span class="nav-number">2.2.1.</span> <span class="nav-text">connect</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Hooks"><span class="nav-number">2.2.2.</span> <span class="nav-text">Hooks</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Todos"><span class="nav-number">2.3.</span> <span class="nav-text">Todos</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#index-js"><span class="nav-number">2.3.1.</span> <span class="nav-text">index.js</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#store-js"><span class="nav-number">2.3.2.</span> <span class="nav-text">store.js</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#reducer-js"><span class="nav-number">2.3.3.</span> <span class="nav-text">reducer.js</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#App-js"><span class="nav-number">2.3.4.</span> <span class="nav-text">App.js</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#create-js"><span class="nav-number">2.3.5.</span> <span class="nav-text">create.js</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#todo-js"><span class="nav-number">2.3.6.</span> <span class="nav-text">todo.js</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#li-js"><span class="nav-number">2.3.7.</span> <span class="nav-text">li.js</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#state-js"><span class="nav-number">2.3.8.</span> <span class="nav-text">state.js</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#中间件"><span class="nav-number">2.4.</span> <span class="nav-text">中间件</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#redux-thunk"><span class="nav-number">2.4.1.</span> <span class="nav-text">redux-thunk</span></a></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Li Yudong"
      src="/images/author.jpg">
  <p class="site-author-name" itemprop="name">Li Yudong</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">95</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">14</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">18</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/tiarmor1" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;tiarmor1" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:1157019137@qq.com" title="E-Mail → mailto:1157019137@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2020 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Li Yudong</span>
</div>

        








      </div>
    </footer>
  </div>

  
  
  <script color='0,0,0' opacity='0.5' zIndex='-1' count='150' src="/lib1/canvas-nest/canvas-nest.min.js"></script>
  <script src="/lib1/anime.min.js"></script>
  <script src="/lib1/velocity/velocity.min.js"></script>
  <script src="/lib1/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  

  
   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;" ></canvas> 
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
   <script type="text/javascript" src="/js/fireworks.js"></script>
  
</body>
</html>

